package source.events.action;

import source.model.AreaEffect;
import source.model.Unit;
import source.model.DataHandler;
import source.model.GameObject;
import source.model.ObjectID;
import source.model.Player;
import source.model.type.ActionResult;
import source.model.type.GameObjectType;
import source.view.MainScreen;
import source.model.Position;

public class UnitNewTurn implements Action{

	private ObjectID unitID;
	
	public UnitNewTurn(ObjectID oid)
	{
		this.unitID = oid;
	}
	public ActionResult execute(DataHandler dh)
	{
		GameObject go = dh.objectQuery(unitID);
		Unit unit;
		if ( go.objectType() != GameObjectType.UNIT) {
			dh.returnObject( go );
			return ActionResult.IMPOSSIBLE;
		}
		unit = (Unit)go;
		Player thatGuy = dh.playerQuery(unit);
		int upkeep = unit.getUpkeep();
		unit.modHealth(-thatGuy.incrementEnergyUsed(upkeep));
		
		// Get area effects for the position the unit is on and 
		// execute the area effect.
		Position p = dh.positionQuery(unitID);
		GameObject[] aes = dh.positionQuery(p, GameObjectType.AREAEFFECT);
		for ( GameObject ae : aes ) {
			if (!((AreaEffect)ae).doEffect( dh, unit )) {
				MainScreen.writeToConsole("Move:  AreaEffect.doEffect() failed");
			}
		}
	
		unit.resetMovement();	
		dh.returnObject(unit);
		return ActionResult.SUCCESS;
	}

}
